package com.wheel.autoconfigure.shiro.filter;

import com.wheel.core.utils.Log;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * shiro
 * 
 * @version 1.0
 * @author NaiFei Wang
 */

public class ShiroLoginFilter extends AuthenticationFilter {


	private static final Logger log = LoggerFactory.getLogger(ShiroLoginFilter.class);

	private String dispatcherLoginConMatch;

	public String getDispatcherLoginConMatch() {
		return dispatcherLoginConMatch;
	}

	public void setDispatcherLoginConMatch(String dispatcherLoginConMatch) {
		this.dispatcherLoginConMatch = dispatcherLoginConMatch;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		boolean r = false;
		if (isLoginRequest(request, response)) {
			r = true;
		} else {
			if (isAjax((HttpServletRequest) request)) {
				throw new AuthenticationException("您尚未登录或登录时间过长,请重新登录!");
			} else {
				saveRequestAndRedirectToLogin(request, response);
			}
		}
		return r;
	}

	/**
	 * 覆写loginUrl验证规则 FilterFactory loginUrl不能直接配置规则，登录会直接使用此地址
	 */
	protected boolean isLoginRequest(ServletRequest request, ServletResponse response) {
		Log.debug(log,"dispatcherLoginConMatch:{},requrl:{}", dispatcherLoginConMatch, request.getRemoteAddr());
		return pathsMatch(getLoginUrl(), request) || pathsMatch(dispatcherLoginConMatch, request);
	}

	/**
	 * <dt>Description:isAjax</dt>
	 * <dd>判断当前请求是否是ajax请求</dd>
	 * <dd>author: wangnaifei@163.com</dd>
	 * <dd>version:1.0 <i>2020/5/13 16:03</i></dd>
	 * @param request
	 * @return boolean
	 * @since jdk1.7+
	 */
	public static boolean isAjax(HttpServletRequest request) {
		String header = request.getHeader("x-requested-with");
		return header!=null && !"".equals(header);
	}

}